<template>
    <el-dialog v-model="dialogFormVisible" :title="flag ? '新增用户' : '修改用户'">
        <el-form :model="form" label-width="auto" :inline="true" label-position="top" :rules="rules" ref="ruleFormRef"
            v-loading="isLoading" element-loading-text="数据加载中...">
            <el-form-item label="账号" prop="userNo">
                <el-input clearable v-model="form.userNo" placeholder="请输入用户账号" style="width: 200px" />
            </el-form-item>
            <el-form-item label="用户名称" prop="username">
                <el-input clearable v-model="form.username" placeholder="请输入用户名" style="width: 200px" />
            </el-form-item>
            <el-form-item label="密码" prop="password" v-if="flag">
                <el-input clearable v-model="form.password" placeholder="请输入登录密码" type="password" show-password
                    style="width: 200px" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
                <el-input clearable v-model="form.phone" placeholder="请输入手机号" style="width: 200px" />
            </el-form-item>
            <el-form-item label="邮箱">
                <el-input clearable v-model="form.email" placeholder="请输入邮箱" style="width: 200px" />
            </el-form-item>
            <el-form-item label="性别">
                <el-select clearable v-model="form.gender" placeholder="请选择性别" style="width: 200px">
                    <el-option label="男" value="0" />
                    <el-option label="女" value="1" />
                </el-select>
            </el-form-item>
            <el-form-item label="角色">
                <el-select clearable v-model="form.roleIds" multiple filterable placeholder="请选择角色"
                    style="width: 200px">
                    <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName"
                        :value="item.roleId" />
                </el-select>
            </el-form-item>
            <el-form-item label="部门">
                <el-tree-select clearable v-model="form.deptId" :data="deptTreeOptions" check-strictly
                    :render-after-expand="false" placeholder="请选择部门" :props="{
                        children: 'children',
                        label: 'deptName',
                        value: 'deptId'
                    }" style="width: 200px" />
            </el-form-item>
            <el-form-item label="岗位">
                <el-select clearable v-model="form.postIds" multiple filterable placeholder="请选择岗位"
                    style="width: 200px">
                    <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName"
                        :value="item.postId" />
                </el-select>
            </el-form-item>
            <el-form-item label="直属上级领导">
                <el-select clearable v-model="form.leaderId" filterable placeholder="请选择直属上级领导" style="width: 200px">
                    <el-option v-for="item in userOptions" :key="item.userId" :label="item.username"
                        :value="item.userId" />
                </el-select>
            </el-form-item>
            <el-form-item label="头像" style="width: 100%">
                <el-upload v-model:file-list="fileList" :class="{ disableUpload: fileList.length > 0 }"
                    :before-upload="beforeAvatarUpload" :headers="header" :action="action"
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleAvatarSuccess"
                    list-type="picture-card" :limit="1">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
            </el-form-item>
            <el-form-item label="用户状态" style="width: 100%px;">
                <el-switch v-model="form.status" :active-value="'0'" :inactive-value="'1'" inline-prompt
                    active-text="正常" inactive-text="禁用" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">返回</el-button>
                <el-button :disabled="isLoading" type="primary" @click="addOrEdit">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup name="addOrEdit">
import { ref, onMounted } from "vue";
import api from "@/api"
import { ElMessage } from 'element-plus'
import { Decrypt } from '@/utils/secret.js'

const isLoading = ref(false)
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const header = ref()
const action = ref(import.meta.env.VITE_BASE_URL + '/system/file/upload?business=用户头像上传')
const fileList = ref([])
const flag = ref(false)
const dialogFormVisible = ref(false)
const form = ref({ status: '0' })
const ruleFormRef = ref()
const roleOptions = ref([])
const deptTreeOptions = ref([])
const postOptions = ref([])
const userOptions = ref([])
const rules = ref({
    userNo: [
        { required: true, message: '请输入用户账号', trigger: 'blur' },
        { min: 5, max: 11, message: '用户账号必须是 5-11位 的字符', trigger: 'blur' }
    ],
    username: [
        { required: true, message: '请输入用户名称', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { pattern: /^\S{6,15}$/, message: '密码必须是 6-15位 的非空字符', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式有误', trigger: 'blur' }
    ]
})
const init = async (userId) => {
    dialogFormVisible.value = true
    isLoading.value = true
    getRoleOptions()
    getDeptTreeOptions()
    getPostOptions()
    getUserOptions()
    if (userId) {
        flag.value = false
        const res = await api.post('/author/user/queryById', { userId: userId })
        if (res.data.code === 200) {
            form.value = res.data.data
            if (res.data.data.headPic) {
                fileList.value = [{
                    name: decodeURIComponent(escape(atob(res.data.data.headPic))),
                    url: import.meta.env.VITE_BASE_URL + '/system/file/download/' + res.data.data.headPic
                }]
            } else {
                fileList.value = []
            }
        } else {
            ElMessage.error(res.data.msg)
        }
    } else {
        flag.value = true
        form.value = { status: '0' }
        fileList.value = []
    }
    isLoading.value = false
}
const getRoleOptions = async () => {
    const res = await api.get('/author/role/pageList', { pageNum: 1, pageSize: 999, status: '0' })
    if (res.data.code === 200) {
        roleOptions.value = res.data.data.records
    } else {
        ElMessage.error(res.data.msg)
    }
}
const getDeptTreeOptions = async () => {
    const res = await api.get('/author/dept/treeData')
    if (res.data.code === 200) {
        deptTreeOptions.value = res.data.data
    } else {
        ElMessage.error(res.data.msg)
    }
}
const getPostOptions = async () => {
    const res = await api.get('/author/post/pageList', { pageNum: 1, pageSize: 999, status: '0' })
    if (res.data.code === 200) {
        postOptions.value = res.data.data.records
    } else {
        ElMessage.error(res.data.msg)
    }
}
const getUserOptions = async () => {
    const res = await api.get('/author/user/pageList', { pageNum: 1, pageSize: 999, status: '0' })
    if (res.data.code === 200) {
        userOptions.value = res.data.data.records
    } else {
        ElMessage.error(res.data.msg)
    }
}
const emit = defineEmits(['serversUpdated']);
const addOrEdit = () => {
    ruleFormRef.value.validate(async (valid) => {
        if (valid) {
            isLoading.value = true
            let url
            if (flag.value) {
                url = '/author/user/add'
            } else {
                url = '/author/user/edit'
            }
            const res = await api.post(url, form.value)
            if (res.data.code === 200) {
                ElMessage.success(res.data.msg)
                emit('serversUpdated')
                dialogFormVisible.value = false
            } else {
                ElMessage.error(res.data.msg)
            }
            isLoading.value = false
        }
    })
}
const beforeAvatarUpload = (file) => {
    const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png');
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG) {
        ElMessage.error('上传头像图片只能是JPG/PNG格式!');
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过2MB!');
    }
    return isJPG && isLt2M;
}
const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
}
const handleRemove = (file) => {
    form.value.headPic = ''
}
const handleAvatarSuccess = (res) => {
    if (res.code === 200) {
        form.value.headPic = res.data
    } else {
        ElMessage.error(res.msg)
    }
}
onMounted(() => {
    const str = window.localStorage.getItem("access-admin")
    const user = JSON.parse(str)
    const token = Decrypt(user.token)
    header.value = { token: token, accessAuthor: 'allow' }
})
defineExpose({
    init
});
</script>
<style scoped></style>